<script setup name="role">
import { nextTick, ref } from "vue"
import { getRoleList, createRole, updateRole, deleteRole, updateRoleStatus, setRoleRules } from "@/api/role"
import { getRuleList } from "@/api/rule"
import { useInitTable, useInitForm } from "@/composables/useCommon"
import FormDialog from "@/components/FormDialog.vue"
import ListHeader from "@/components/ListHeader.vue"

// 虚拟化树形控件高度
const treeHeight = ref(0)
// 配置权限弹窗节点
const setRoleDialogRef = ref(null)
// 角色列表
const ruleList = ref([])
// 虚拟化树形控件配置
const treeProps = {
  label: "name",
  children: "child"
}
// 当前修改的角色ID
const roleId = ref(0)
// 默认展开节点数组
const defaultExpandedKeys = ref([])
// 树组件节点
const elTreeRef = ref()
// 当前用户所拥有角色
const ruleIds = ref([])
// 父子不互相关联
const checkStrictly = ref(false)

// 引入公共方法
const { windowHeight, tableData, loading, currentPage, total, limit, getData, handleDelete, handleStatusChange, toast } = useInitTable({
  getList: getRoleList,
  delete: deleteRole,
  updateStatus: updateRoleStatus
})

// 解构表单公共方法
const { form, dialogRef, formRef, rules, dialogTitle, handleSubmit, handleCreate, handleEdit, resetForm } = useInitForm({
  getData,
  updata: updateRole,
  create: createRole,
  form: {
    name: "",
    desc: "",
    status: 1
  },
  rules: {
    name: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    desc: [{ required: true, message: "角色描述不能为空", trigger: "blur" }],
    status: [{ required: true, trigger: "blur" }]
  }
})

// 减去头部高度、标签高度、内边距高度
let h = windowHeight.value - 64 - 44 - 36
const h2 = windowHeight.value - 64 - 44 - 110

// 提交权限配置
const handleSetRuleSubmit = async () => {
  // 显示按钮加载
  setRoleDialogRef.value.showLoading()
  // 调用请求方法
  await setRoleRules(roleId.value, ruleIds.value)
  // 弹出提示
  toast("配置成功")
  // 刷新数据
  getData()
  // 关闭按钮加载
  setRoleDialogRef.value.hideLoading()
  // 隐藏弹窗
  setRoleDialogRef.value.close()
}

// 配置权限
const openSetRule = async row => {
  // 保存当前角色的id
  roleId.value = row.id
  // 获取视口可视高度赋值给虚拟树组件
  treeHeight.value = window.innerHeight - 390
  // 父子不互相关联
  checkStrictly.value = true
  // 调用请求方法
  const res = await getRuleList(1)
  // 赋值数据
  ruleList.value = res.list
  // 显示弹窗
  setRoleDialogRef.value.open()
  // 获取默认展开一级节点数据
  defaultExpandedKeys.value = res.list.map(val => val.id)
  // 获取当前角色所拥有的权限
  ruleIds.value = row.rules.map(i => i.id)
  // 延迟展示勾选默认选中
  nextTick(() => {
    elTreeRef.value.setCheckedKeys(ruleIds.value)
    checkStrictly.value = false
  })
  // setTimeout(() => elTreeRef.value.setCheckedKeys(ruleIds.value), 0)
}

// 节点选中事件
const handleTreeCheck = (...e) => {
  // 解构数组数据
  const { checkedKeys, halfCheckedKeys } = e[1]
  // 展开后存入当前用户所拥有角色数据
  ruleIds.value = [...checkedKeys, ...halfCheckedKeys]
}
</script>

<template>
  <el-card shadow="never" :body-style="{ 'padding-bottom': '10px', 'padding-left': '0', 'padding-right': '0' }" :style="{ height: `${h}px` }">
    <ListHeader create="新增角色" @create="handleCreate" @refresh="getData" />
    <div class="card-table" :style="{ height: `${h2}px` }">
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="name" min-width="80" label="角色名称" fixed />

        <el-table-column label="角色描述" min-width="120">
          <template #default="{ row }">
            {{ row.desc ? row.desc : "-" }}
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              size="small"
              :active-value="1"
              :inactive-value="0"
              :loading="row.statusLoading"
              style="--el-switch-on-color: #13ce66"
              @change="handleStatusChange($event, row)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" min-width="90">
          <template #default="{ row }">
            <el-tooltip effect="light" content="配置权限" placement="left">
              <el-icon @click="openSetRule(row)">
                <Setting />
              </el-icon>
            </el-tooltip>
            <el-tooltip effect="light" content="修改" placement="top">
              <el-icon @click="handleEdit(row)" class="edit">
                <Edit />
              </el-icon>
            </el-tooltip>
            <el-popconfirm width="180" title="是否要删除该角色？" confirmButtonText="确认" cancelButtonText="取消" @confirm="handleDelete(row.id)">
              <template #reference>
                <el-icon>
                  <CloseBold />
                </el-icon>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" :image-size="200" />
        </template>
      </el-table>
      <!-- 分页 -->
      <div class="role-pagination">
        <el-pagination background small layout="prev, pager, next" :total="total" :current-page="currentPage" :page-size="limit" :hide-on-single-page="total < 11" @current-change="getData" />
      </div>
    </div>
    <!-- 权限配置 -->
    <FormDialog ref="setRoleDialogRef" top="7.6vh" :width="40" title="权限配置" @submit="handleSetRuleSubmit">
      <el-tree-v2
        ref="elTreeRef"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        :data="ruleList"
        :check-strictly="checkStrictly"
        :props="treeProps"
        :height="treeHeight"
        show-checkbox
        @check="handleTreeCheck"
      >
        <template #default="{ node, data }">
          <div class="tree-tag">
            <el-tag :type="data.menu ? '' : 'info'" size="small" effect="plain">
              {{ data.menu ? "菜单" : "权限" }}
            </el-tag>
            <span>{{ data.name }}</span>
          </div>
        </template>
      </el-tree-v2>
    </FormDialog>
    <!-- 修改角色 -->
    <FormDialog ref="dialogRef" :width="60" :title="dialogTitle" @submit="handleSubmit" @close="resetForm">
      <el-form :model="form" ref="formRef" :rules="rules" :inline="false">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入角色描述" type="textarea" :rows="5" />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-switch v-model="form.status" size="small" :active-value="1" :inactive-value="0" style="--el-switch-on-color: #13ce66" />
        </el-form-item>
      </el-form>
    </FormDialog>
  </el-card>
</template>

<style lang="scss" scoped>
.el-card {
  border: 0;
  overflow-y: auto;

  .card-table {
    display: flex;
    justify-content: space-between;
    flex-direction: column;

    .el-table {
      z-index: 0;
      .el-icon {
        cursor: pointer;
      }
      .edit {
        margin: 0 10px;
      }
      :deep(.el-table__row) {
        height: 6.8vh;
      }
    }

    .role-pagination {
      display: flex;
      justify-content: center;
      padding-top: 10px;
    }
  }
  .tree-tag {
    display: flex;
    align-items: center;
    .el-tag {
      margin-right: 8px;
    }
  }
}

@media screen and (max-width: 375px), screen and (max-width: 414px) {
  :deep(.el-dialog--center) {
    min-width: 70% !important;
    max-width: 70% !important;
  }
  :deep(.el-table__row) {
    height: 6.6vh;
  }
}
</style>
